String.prototype.format = function(args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof(args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        } else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题
                    var reg = new RegExp("({)" + i + "(})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}
var ShowAuthor = false;
var Splay = function(container, dict) {
    this.version = "0.0.0.5";
    this.showAuthor = function() {
        if (!ShowAuthor) {
            console.log("%c  %c\n\n %cSplay version：{0} By 2020  晚安 %c\n".format(this.version), "background: url(https://www.ludanblog.xyz/static/egg.svg) no-repeat center;padding-left:130px;padding-bottom: 130px;", "", "color:white;background:#cb814c;border-radius:5px;padding:10px;", "");
            ShowAuthor = !ShowAuthor;
        }
    }
    this.addStorage = function(key, value) {
        var data = this.getStorage(this.dict.storageName, {});
        for (var item in value) {
            data[item] = value[item];
        }
        this.setStorage(key, data);
    }
    this.setStorage = function(key, value) {
        return localStorage.setItem(key, JSON.stringify(value));
    }
    this.getStorage = function(key, value) {
        return JSON.parse(localStorage.getItem(key)) || value;
    }
    var defaults = {
        defaultLrc:"[00:00.000] 纯音频，请听享",
        autoplay: false,
        //自动播放 现在大多数浏览禁用自动播放
        loop: false,
        //自动循环播放单曲
        //volume: 0.7, //音频播放
        preload: "auto",
        //auto - 载入整个音频 meta - 只载入元数据 none - 不载入音频
        storageName: "Splay-setting",
        //保存storage信息 key
        audio: [{
            name: "",
            //歌曲名字
            cover: "",
            //封面
            src: "",
            //歌曲源文件
            artist: "",
            //作者
            lrc: ""
            //歌词
        }],
    };
    this.dict = this.extend(defaults, dict);
    var setting = this.getStorage(this.dict.storageName, false);
    this.volume = this.dict.volume || setting ? setting.volume: 0.7;
    var that = this;
    that.dict.audio.forEach(function(music, i) {
        that.dict.audio[i].name = music.name || "";
        that.dict.audio[i].cover = music.cover || "";
        that.dict.audio[i].src = music.src || "";
        that.dict.audio[i].artist = music.artist || "";
        that.dict.audio[i].lrc = music.lrc || "";
    });
    this.reverse = 1; // 1 = 垂直 2 = 水平
    this.container = container || document.querySelector(".splay");
    this.isMobile = /mobile/i.test(window.navigator.userAgent);
    this.audio = null;
    this.music = this.dict.audio[0];
    this.musicIndex = 0; //当前音乐索引
    this.isPlay = false;
    this.lineNo = 0; //当前行
    this.C_pos = 1; //C位
    this.offset = -20; //滚动距离（应等于行高）
    this.duration = 0;
    this.coverTimer = null;
    this.lrc = {
        ti: "",
        //歌曲名
        ar: "",
        //演唱者
        al: "",
        //专辑名
        by: "",
        //歌词制作人
        offset: 0,
        //时间补偿值，单位毫秒，用于调整歌词整体位置
        ms: [] //歌词数组{t:时间,c:歌词}
    };
    this.init = function(reverse) { //音频初始化函数
        var that = this;
        that.reverse = reverse || 1;
        that.container.innerHTML = "";
        that.setAudio();
        that.setHtml();
        that.setMusic(0);
    };
};
Splay.prototype.setHtml = function() {
    var that = this;
    var style = "",drag = null,volumeDrag=null;
    if (that.reverse === 2) {
        var style = "<style>.splay {display: flex;justify-content: space-around;} .splay .splay-info,.splay .splay-box{width: 50%; max-width: 50%;display: flex;flex-direction: column;justify-content: center;}"+
            ".splay .splay-info{} .splay .splay-box{}</style>";
        that.container.style.height = "60vh";
    }else{
        var style = "<style>.splay {display: flex;justify-content: space-around;flex-direction: column;flex-direction: column;} .splay .splay-info,.splay .splay-box{width: 100%; max-width: 100%;display: flex;flex-direction: column;justify-content: center;}"+
            ".splay .splay-info{} .splay .splay-box{}</style>";
        that.container.style.height = "90vh";
    }
    var html = style + '<div class="splay-info"><div class="splay-info-box"><img class="splay-cover" src="https://www.svvwp.com/static/svg/logo.svg" data-rotate="0"/><br/><h4 class="splay-title"></h4></div></div>' + '<div class="splay-box"><div style="position: relative;"><div class="splay-lyric-area"><ul class="splay-lyric"></ul></div></div></div>';
    that.container.className = "splay";
    that.container.innerHTML = html;
    var box = document.querySelector("div.splay>div.splay-box");
    var div = document.createElement("div");
    var controller = document.createElement("div");
    var progressBar = document.createElement("div");
    var playProgressBar = document.createElement("div");
    var circular = document.createElement("div");

    var volume = document.createElement("div");
    var volumeprogress = document.createElement("div");
    var volumeprogressBar = document.createElement("div");

    var timer = document.createElement("div");
    var cuTime = document.createElement("span");
    var duration = document.createElement("span");
    var btn = document.createElement("span");
    var prevbtn = document.createElement("span");
    var Nextbtn = document.createElement("span");

    box.className = "splay-box";
    controller.className = "splay-controller";
    progressBar.className = "splay-progressBar";
    playProgressBar.className = "splay-playProgressBar";
    circular.className = "splay-circular";

    volume.className = "splay-volume splay-{0}".format(that.volume ? "noise": "mute");
    volume.dataset.volume = that.volume;
    volumeprogress.className = "splay-volumeProgress";
    volumeprogressBar.className = "splay-volumeProgressBar";

    btn.className = "splay-btn-play";
    btn.id = "splay-btn-ctrl";
    timer.className = "splay-timer";
    duration.className = "splay-dtime";
    cuTime.className = "splay-ptime";

    // if(that.isMobile){
    progressBar.style.width = "80%";
    // }
    btn.innerHTML = "<span></span>";
    btn.onclick = function() {
        that.togglePlay();
        btn.title = this.isPlay ? "暂停音乐": "播放音乐";
    };
    btn.title = this.isPlay ? "暂停音乐": "播放音乐";
    prevbtn.className = "splay-btn-prev";
    Nextbtn.className = "splay-btn-next";
    prevbtn.innerHTML = "<span></span>";
    Nextbtn.innerHTML = "<span></span>";
    if (that.musicIndex === 0) {
        prevbtn.style.display = "none";
    }
    if (that.dict.audio.length === 1) {
        Nextbtn.style.display = "none";
    }
    prevbtn.onclick = function() {
        if (that.musicIndex > 0) {
            that.setMusic(that.musicIndex - 1);
        }
    }
    Nextbtn.onclick = function() {
        if (that.musicIndex < that.dict.audio.length - 1) {
            that.setMusic(that.musicIndex + 1);
        }
    }
    div.className = "splay-btns";
    div.appendChild(prevbtn);
    div.appendChild(btn);
    div.appendChild(Nextbtn);
    // Nextbtn.getElementsByTagName("span").style.;
    progressBar.appendChild(playProgressBar);
    progressBar.appendChild(circular);
    controller.appendChild(progressBar);
    /*
    if (!that.isMobile && false) {
        controller.appendChild(volume);
        volumeprogressBar.appendChild(volumeprogress);
        var volumeTimer = null;
        volume.onmouseover = volumeprogressBar.onmouseover = function(){
            clearTimeout(volumeTimer);
            volumeprogressBar.style.display = "block";
        }
        volume.onmouseout = volumeprogressBar.onmouseout = function(){
            clearTimeout(volumeTimer);
            volumeTimer = setTimeout(function() {
                volumeprogressBar.style.display = "none";
            }, 200);
        }
        controller.appendChild(volumeprogressBar);
        volumeprogressBar.onclick = function(e) {
            e = e || window.event;
            var touches = e.touches;
            if (e.pageX || e.pageY) {
                touches = [{
                    pageX: e.pageX
                }]
            } else if (e.clientX || e.clientY) {
                touches = [{
                    pageX: e.clientX
                }]
            }
            that.setVolume(getVolume(that, touches))
        };
        function getVolume(that,touches){
		    var progressBar = document.querySelector("div.splay-controller > div.splay-volumeProgressBar"),
		    playProgressBar = document.querySelector("div.splay-controller > div.splay-volumeProgressBar > div.splay-volumeProgress")
		    var sp = touches[0].offsetX / progressBar.offsetWidth;
		    playProgressBar.style.width = "{0}%".format(sp*100);
		    sp = Math.max(sp, 0);
		    sp = Math.min(sp, 1);
		    console.log(sp);
		    return sp;
		}
		//volumeDrag = new Drag(,that.setVolume(volume,function(){},function(){getVolume(that,touches))})
    } //未开发完成，或许删除，此段代码保留
    */
    timer.appendChild(cuTime);
    try{
        timer.append(" / ");
    }catch(e){
        var temphtml = document.createElement("span");
        temphtml.innerHTML=" / ";
        timer.appendChild(temphtml);
    }
    timer.appendChild(duration);

    box.appendChild(div);
    box.appendChild(controller);
    box.appendChild(timer);
    that.container.appendChild(box);

    var progress = document.querySelector("div.splay-controller>div.splay-progressBar");
    if (progress) {
        drag = new Drag(progress,function(){
        },function(touch,touches){
            if(drag.element.offsetWidth){
                var cTime = that.audio.duration * ((touch.x - touches.left) / drag.element.offsetWidth);
                cTime = Math.max(cTime, 0);
                cTime = Math.min(cTime, that.audio.duration);
                that.audio.currentTime = cTime;
            }
        },function(){
            that.ctrlLrc.goback(that);
            that.SplayTimer = setInterval(function(){
                try{
                    var percent  = that.audio.currentTime / that.audio.duration;
                    document.querySelector(".splay-playProgressBar").style.width = "{0}%".format(percent * 100);
                    if(that.lineNo==that.lrc.ms.length){return;}
                    var curTime = that.audio.currentTime; //播放器时间
                    if(parseFloat(that.lrc.ms[that.lineNo].t)<=curTime){
                        that.ctrlLrc.lineHigh(that);//高亮当前行
                        that.lineNo++;
                    }else{clearInterval(that.SplayTimer)}
                }catch(e){clearInterval(that.SplayTimer)}
            },1);
        })
        
        progress.onclick = function(e) {
            e = e || window.event;
            
            if(!e.touches) {  //兼容移动端
                //Move && Move(Dthat.getPosition(Dthat.element));
                var touches = {x:e.clientX,y:e.clientY};
            } else {   //兼容PC端
                //Move && Move(Dthat.getPosition(Dthat.element));
                var touches = {x:e.touches[0].pageX,y:e.touches[0].pageY};
            }
            var cTime = that.audio.duration * ((touches.x- drag.getPosition(drag.element).left) / drag.element.offsetWidth);
            cTime = Math.max(cTime, 0);
            cTime = Math.min(cTime, that.audio.duration);
            that.audio.currentTime = cTime;
        };
    }
};
Splay.prototype.setMusic = function(index) {
    var that = this;
    that.musicIndex = index;
    clearInterval(that.coverTimer);
    that.lineNo = 0 ;
    that.lrc = {
        ti: "",
        //歌曲名
        ar: "",
        //演唱者
        al: "",
        //专辑名
        by: "",
        //歌词制作人
        offset: 0,
        //时间补偿值，单位毫秒，用于调整歌词整体位置
        ms: [] //歌词数组{t:时间,c:歌词}
    };
    this.music = that.dict.audio[index];
    var music = this.music;
    that.audio.src = music.src;
    var cover = document.querySelector("div.splay div.splay-info .splay-cover"),
    title = document.querySelector("div.splay div.splay-info .splay-title");
    cover.style.transform = "rotate(0deg)";
    cover.dataset.rotate = "0";
    cover.src = music.cover;
    if(music.artist){
        title.innerHTML = '{0}<span>  -  {1}<span></span></span>'.format(music.name,music.artist)
    }else{
        title.innerText = music.name;
    }

    var prev = document.querySelector("div.splay > .splay-box > .splay-btns > .splay-btn-prev");
    var next = document.querySelector("div.splay > .splay-box > .splay-btns > .splay-btn-next");
    prev.style.display = index === 0 ? "none": "inline-block";
    next.style.display = that.dict.audio.length - 1 === index ? "none": "inline-block";
    // 可考虑换成 background #919191  暂行display none

    that.audio.onloadeddata = function() {
        document.querySelector("div.splay-timer>span.splay-ptime").innerText = "0:00";
        document.querySelector("div.splay-timer>span.splay-dtime").innerText = formatSeconds(that.audio.duration);
        that.getLRC(music.lrc || "",
        function(res) {
            try{
                that.createLrcObj(res, that.lrc);
            }catch(e){
                that.createLrcObj(that.dict.defaultLrc, that.lrc);
            }
            that.showLRC(that.lrc, ".splay-lyric");
            that.audio.addEventListener("timeupdate",
            function() {
                try {
                    if (that.lineNo == that.lrc.ms.length) {
                        return;
                    }
                    var curTime = that.audio.currentTime; //播放器时间
                    if (parseFloat(that.lrc.ms[that.lineNo].t) <= curTime) {
                        that.ctrlLrc.lineHigh(that); //高亮当前行
                        that.lineNo++;
                    };
                    //获取当前播放的百分比  当前进度/总进度
                    var percent = that.audio.currentTime / that.audio.duration;
                    document.querySelector(".splay-playProgressBar").style.width = "{0}%".format(percent * 100);
                    document.querySelector("div.splay-controller>div.splay-progressBar > div.splay-circular").style.left = "{0}%".format((percent * 100) - (that.isMobile ? 1 : 0.5));
                    document.querySelector("div.splay-timer>span.splay-ptime").innerText = formatSeconds(that.audio.currentTime);
                    document.querySelector("div.splay-timer>span.splay-dtime").innerText = formatSeconds(that.audio.duration);
                } catch(e) {
                    console.log(e)
                }
            },
            false)
        });
    }
    that.audio.onended = function() {
        if (that.dict.audio.length - 1 === index) {
            that.ctrlLrc.goback(that);
            document.querySelector("div.splay-controller > div.splay-progressBar > div.splay-circular").style.left = "";
        } else {
            that.setMusic(that.musicIndex + 1)
        }
    };
    //var cover = document.querySelector("div.splay>div:nth-child(1)>img.splay-cover");
    that.audio.onpause = function() {
        //cover.className = "splay-cover";
        clearInterval(that.coverTimer);
        document.querySelector("#splay-btn-ctrl").className = "splay-btn-play"
    };
    that.audio.onplay = function() {
        //cover.className = "splay-cover rotate";
        that.coverTimer = setInterval(function() {
            if (!document[hiddenProperty]) { 
                cover.style.transform = "rotate({0}deg)".format(cover.dataset.rotate);
                cover.dataset.rotate = parseInt(cover.dataset.rotate) >= 7200000 ? 0 : parseInt(cover.dataset.rotate) + 1;
            }
        },
        200) //coverTimer
        document.querySelector("#splay-btn-ctrl").className = "splay-btn-pause"
    };
    if (that.isPlay) {
        that.audio.play()
    }
};
Splay.prototype.setAudio = function(url, callback) {
    var that = this;
    this.showAuthor();
    this.audio = document.createElement('audio');
    //this.audio.setAttribute("muted",true);
    this.audio.controls = false;
    this.audio.autoplay = this.dict.autoplay || false;
    this.audio.loop = that.dict.loop || false;
    this.audio.volume = that.volume;
    this.audio.preload = that.dict.preload || "auto";
    this.audio.src = that.dict.audio[0].src;
    if (that.audio.autoplay === true) {
        that.is_play = true;
        that.play(0,
        function() {
            console.log("自动播放失败");
            that.is_play = false
        });
    };
};
Splay.prototype.showLRC = function(oLRC, id) {
    var s = "";
    for (var i in oLRC.ms) { //遍历ms数组，把歌词加入列表
        if(oLRC.ms[i].c){
            s += '<li>' + oLRC.ms[i].c + '</li>';
        }
    }
    document.querySelector(id || ".splay-lyric").innerHTML = s;
}
Splay.prototype.createLrcObj = function(lrc, oLRC) {
    var that = this;
    if (lrc.length == 0) {
        return;
    }
    var lrcs = lrc.split('\n'); //用回车拆分成数组
    for (var i in lrcs) { //遍历歌词数组
        try{
            lrcs[i] = lrcs[i].replace(/(^\s*)|(\s*$)/g, ""); //去除前后空格
            var t = lrcs[i].substring(lrcs[i].indexOf("[") + 1, lrcs[i].indexOf("]")); //取[]间的内容
            var s = t.split(":"); //分离:前后文字
            if (isNaN(parseInt(s[0]))) { //不是数值
                for (var i in oLRC) {
                    if (i != "ms" && i == s[0].toLowerCase()) {
                        oLRC[i] = s[1];
                    }
                }
            } else { //是数值
                var arr = lrcs[i].match(/\[(\d+:.+?)\]/g); //提取时间字段，可能有多个
                var start = 0;
                for (var k in arr) {
                    start += arr[k].length; //计算歌词位置
                }
                var content = lrcs[i].substring(start); //获取歌词内容
                for (var k in arr) {
                    var t = arr[k].substring(1, arr[k].length - 1); //取[]间的内容
                    var s = t.split(":"); //分离:前后文字
                    oLRC.ms.push({ //对象{t:时间,c:歌词}加入ms数组
                        t: (parseFloat(s[0]) * 60 + parseFloat(s[1])).toFixed(3),
                        c: content
                    });
                }
            }
        }catch(e){}
    }
    oLRC.ms.sort(function(a, b) { //按时间顺序排序
        return a.t - b.t;
    });
    var end = {
        t: (that.audio.duration).toFixed(3).toString(),
        c: " "
    }; //补全歌词进度条
    if (that.lrc.ms.length > 2) {
        if (formatSeconds(that.lrc.ms[that.lrc.ms.length - 1].t) !== formatSeconds(end)) {
            that.lrc.ms.push(end)
        }
    } else {
        that.lrc.ms = [{
            t: "0.000",
            c: ""
        }];
        that.lrc.ms.push({
            t: "0.000",
            c: "纯音频，请听享"
        });
        that.lrc.ms.push(end);
    }
    oLRC.ms.forEach(function(ms, i) {
        if (ms.c === "") {
            that.lrc.ms[i].c = " ";
        }
    })
    /*
    for(var i in oLRC){ //查看解析结果
        console.log(i,":",oLRC[i]);
    }*/
}
Splay.prototype.getLRC = function(url, callback) {
    var that = this;
    if (url === "" || typeof url != 'string') {
        callback && callback(that.dict.defaultLrc);
    }else {
        try{
            url = url || "";
            var xhr = new createXmlHttp();
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200 || xhr.status == 302) {
                        callback && callback(xhr.responseText);
                    }
                }
            }
            xhr.onerror = function(){
                callback && callback(url);
            }
            xhr.open("GET", "{0}".format(url), true);
            xhr.send(null);
        }catch(e){
            callback && callback(that.dict.defaultLrc);
        }
    }
};
Splay.prototype.checkURL = function(url){
    if(!url){return false;}
    return new RegExp(/^(?:(file|http|https|ftp):\/\/)?((?:[\w-]+\.)+[a-z0-9]+)((?:\/[^/?#]*)+)?(\?[^#]+)?(#.+)?$/ig).test(url);
}
Splay.prototype.extend = function() {
    var length = arguments.length;
    var target = arguments[0] || {};
    if (typeof target != "object" && typeof target != "function") {
        target = {};
    }
    if (length == 1) {
        target = this;
        i--;
    }
    for (var i = 1; i < length; i++) {
        var source = arguments[i];
        for (var key in source) {
            // 使用for in会遍历数组所有的可枚举属性，包括原型。
            if (Object.prototype.hasOwnProperty.call(source, key)) {
                target[key] = source[key];
            }
        }
    }
    return target;
}
Splay.prototype.togglePlay = function() {
    var that = this;
    if (that.isPlay) {
        that.pause()
    } else {
        that.play();
    }
}
Splay.prototype.pause = function() {
    if (this.audio.played) {
        this.audio.pause();
        this.isPlay = !this.isPlay;
    }
};
Splay.prototype.play = function(time, error) {
    var that = this;
    if (Object.prototype.toString.call(time) === '[object Number]') {
        time = Math.max(time, 0);
        time = Math.min(time, that.duration);
        that.audio.currentTime = time.toFixed(6);
    }
    if (that.audio.paused) {
        try{
            that.audio.play().catch(function(err) {
                error && error(err);
                console.log(err);
            });
        }catch(e){
            that.audio.play()
        }
        that.isPlay = !that.isPlay;
    }
};
Splay.prototype.destroy = function() {
    this.audio.pause();
    this.container.innerHTML = '';
    this.audio.src = '';
    this.audio = null;
    //销毁
};
Splay.prototype.setVolume = function(volume) {
    this.audio.volume = volume;
    this.addStorage(this.dict.storageName, {
        volume: volume
    })
};
Splay.prototype.ctrlLrc = {
    //高亮显示歌词当前行及文字滚动控制，行号为lineNo
    lineHigh: function(that, ul) {
        try{
            ul = ul || document.querySelector(".splay-lyric");
            var lis = ul.getElementsByTagName("li"); //歌词数组
            if (that.lineNo > 0) {
                lis[that.lineNo - 1].removeAttribute("class"); //去掉上一行的高亮样式
            }
            lis[that.lineNo].className = "lineHigh"; //高亮显示当前行
            //文字滚动
            if (that.lineNo > that.C_pos) {
                ul.style.transform = "translateY(" + (that.lineNo - that.C_pos) * that.offset + "px)"; //整体向上滚动一行高度
            }
        }catch(e){}
    },
    //滚回到开头，用于播放结束时
    goback: function(that, id, ul) {
        try{
            ul = ul || document.querySelector(".splay-lyric");
            document.querySelector("div.splay-controller > div.splay-progressBar > div.splay-playProgressBar").style.width = "";
            document.querySelector("div.splay-controller > div.splay-progressBar > div.splay-circular").style.left = "";
            document.querySelector(id || ".splay-lyric .lineHigh").removeAttribute("class");
            ul.style.transform = "translateY(0)";
            that.lineNo = 0;
        }catch(e){}
    }
}

function formatSeconds(value) {
    function zeroFill(num) {
        return num >= 10 ? num: "0{0}".format(num);
    }
    var theTime = parseInt(value); // 秒
    
    var middle = 0; // 分
    
    var hour = 0; // 小时
    
    if (theTime > 60) {middle = parseInt(theTime / 60);theTime = parseInt(theTime % 60);
        if (middle > 60) {hour = parseInt(middle / 60);middle = parseInt(middle % 60);
        } else if (middle == 60) {hour += 1;middle = 0;
        }
    } else if (theTime == 60) {middle += 1;theTime = 0;
    }
    var result = "0:{0}".format(zeroFill(theTime));
    if (middle > 0) {result = "{0}:{1}".format(zeroFill(middle), zeroFill(theTime));
    }
    if (hour > 0) {result = "{0}:{1}:{2}".format(zeroFill(hour), zeroFill(middle), zeroFill(theTime));
    }
    return result;
}

function createXmlHttp() {
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest()
    } else if (window.ActiveXObject) {
        try {
            return new ActiveObject("Microsoft.XMLHTTP")
        } catch(e) {
            try {
                return new ActiveObject("Msxml2.XMLHTTP")
            } catch(e) {}
        }
    }
};
var hiddenProperty = 'hidden' in document ? 'hidden' :    
    'webkitHidden' in document ? 'webkitHidden' :    
    'mozHidden' in document ? 'mozHidden' :    
    null;

var Drag = function (element,Start,Move,End){
    var Dthat = this;
    this.ifBool = false; //判断鼠标是否按下
    if(element){
        this.element = element;
    }else{console.error("错误的节点");return null;}
    this.start = function(e) {
        e.stopPropagation();
        Dthat.ifBool = true;
        //console.log("鼠标按下")
        Start && Start(e);
    };
    this.move = function(e) {
        //console.log("鼠标拖动")
        if(Dthat.ifBool) {
            if(!e.touches) {  //兼容移动端
                Move && Move({x:e.clientX,y:e.clientY}, Dthat.getPosition(Dthat.element));
            } else {   //兼容PC端
                Move && Move({x:e.touches[0].pageX,y:e.touches[0].pageY}, Dthat.getPosition(Dthat.element));
            }

        }
    };
    this.end = function(e) {
        //console.log("鼠标弹起")
        Dthat.ifBool = false;
        End && End(e);
        window.addEventListener("touchmove",function(){},false);
        window.addEventListener("touchend",function(){},false);
        window.addEventListener("mousemove",function(){},false);
        window.addEventListener("mouseup",function(){},false);
    };
    this.getPosition = function (node) {//获取元素的绝对位置
        var left = node.offsetLeft; //获取元素相对于其父元素的left值var left
        var top = node.offsetTop;
        var current = node.offsetParent; // 取得元素的offsetParent
        // 一直循环直到根元素
        while(current != null) {
            left += current.offsetLeft;
            top += current.offsetTop;
            current = current.offsetParent;
        }
        return {left: left,top: top};
    }
    Dthat.element.addEventListener("touchstart", function(e){
        Dthat.start(e || window.event);
        window.addEventListener("touchmove", Dthat.move,false);//拖动
        window.addEventListener("touchend", Dthat.end,false);//松开
    },false);//按下
    Dthat.element.addEventListener("mousedown", function(e){
        Dthat.start(e || window.event);
        window.addEventListener("mousemove", Dthat.move,false);
        window.addEventListener("mouseup", Dthat.end,false);
    },false);
}